package com.dss.code_generation.config;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;

/**
 * @author: dongshoushan
 * @date: 2021年06月07日 15:41
 */
@Configuration
@EnableAsync
public class ExecutePoolConfiguration {
    /**
     * 自定义线程池
     * @return
     */
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setKeepAliveSeconds(300);
        //核心线程池数
        pool.setCorePoolSize(10);
        // 最大线程
        pool.setMaxPoolSize(20);
        //队列容量
        pool.setQueueCapacity(40);
        //队列满，线程被拒绝执行策略
        pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
        pool.setThreadNamePrefix("dss-");
        return pool;
    }

    /**
     * 定时任务线程池
     * @return
     */
    @Bean(name = "scheduledThreadPoolExecutor")
    public ScheduledThreadPoolExecutor scheduledThreadPoolExecutor() {
        ThreadFactory factory = new ThreadFactoryBuilder().setNamePrefix("file-thread-").build();
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(20, factory);
        return executor;
    }
}

